package com.utility.httpclient;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtility {
	/**
	 * 将JSON格式的字符串转换成给定的实体类
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static <T> T strToEntity(String json,Class<T> clazz) {
		try{
			return objectMapper.readValue(json, clazz);
		}catch(IOException e) {
			return null;
		}
	}
	
	/**
	 * 将实体类转换为JSON格式字符串
	 * @param source
	 * @return
	 */
	public static String entityToStr(Object source) {
		try {
			return objectMapper.writeValueAsString(source);
		} catch (JsonProcessingException e) {
			return null;
		}
	}
	
	
	private static ObjectMapper objectMapper = new ObjectMapper();
	static {
		// 在遇到未知属性的时候不抛出异常
		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
	}
}
